// @flow
import React, { Component } from 'react';
import OutsideClickHandler from 'react-outside-click-handler';
import cx from 'classnames';

import './Editable.scss';

type Props = {
  classPref: string,
  id: string,
  editType: string,
  editableIds: Array<string>,
  placeholder: string,
  value: string,
  onEditablItemChange({ id: string, value: string }): void,
  onEditableItemOutClick(id: string): void,
  onEditableItemDoubleClick(id: string): void,
};

class Editable extends Component<Props> {
  render() {
    const {
      classPref,
      id,
      editType,
      editableIds,
      placeholder,
      value,
      onEditablItemChange,
      onEditableItemDoubleClick,
      onEditableItemOutClick,
    } = this.props;
    // console.log(editableIds);
    const index = editableIds.indexOf(`editableItem_${editType}-${id}`);
    return (
      <OutsideClickHandler
        onOutsideClick={() => {
          onEditableItemOutClick(`editableItem_${editType}-${id}`);
        }}
      >
        <input
          id={`editableItem_${editType}-${id}`}
          className={cx('Editable-input', classPref === '' ? 'editable' : classPref)}
          type="text"
          readOnly={index === -1}
          placeholder={placeholder}
          value={value}
          onDoubleClick={(e) => {
            onEditableItemDoubleClick(`editableItem_${editType}-${id}`);
          }}
          onChange={(e) => {
            // console.log(editableIds);
            // console.log(e.target.value);
            onEditablItemChange({ id: `editableItem_${editType}-${id}`, value: e.target.value });
          }}
        />
      </OutsideClickHandler>
    );
  }
}

export default Editable;
